package com.yihu.wlyy.service.app.account;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.yihu.wlyy.entity.doctor.DoctorPatient;
import com.yihu.wlyy.entity.doctor.DoctorPatientGroup;
import com.yihu.wlyy.entity.doctor.DoctorPatientGroupInfo;
import com.yihu.wlyy.repository.DoctorPatientDao;
import com.yihu.wlyy.repository.DoctorPatientGroupDao;
import com.yihu.wlyy.repository.DoctorPatientGroupInfoDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.util.DateUtil;

/**
 * 医生端：患者管理业务处理类
 * @author George
 *
 */
@Component
@Transactional(rollbackFor = Exception.class)
public class DoctorPatientGroupService extends BaseService {

	@Autowired
	private DoctorPatientGroupDao doctorPatientGroupDao;
	@Autowired
	private DoctorPatientGroupInfoDao doctorPatientGroupInfoDao;
	@Autowired
	private DoctorPatientDao doctorPatientDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 查询医生下所有的慢病人员
	 * @param doctor
	 * @return
	 */
	public JSONObject findDiseasePatient(String doctor) {
		// a.code, a.name, a.photo, a.sex, a.birthday, b.signType
		List<Object> patients = doctorPatientDao.findPatientByDisease(doctor, 1);
		return buildPatient(patients, "1", "健康人群");
	}
	
	public JSONObject countDiseasePatient(String doctor){
		JSONObject object = new JSONObject();
		object.put("code", "1");
		object.put("name", "慢病人群");
		object.put("total", doctorPatientDao.countByDoctorAndDisease(doctor, 1));
		
		return object;
	}
	
	public JSONObject countNormalPatient(String doctor){
		JSONObject object = new JSONObject();
		Date date = DateUtil.strToDateShort(DateUtil.getNextYear(new Date(), -65));
		object.put("code", "1");
		object.put("name", "普通人群");
		object.put("total", doctorPatientDao.countNormalPatient(doctor, 1, date));
		
		return object;
	}
	
	public JSONObject countOldPatient(String doctor){
		JSONObject object = new JSONObject();
		Date date = DateUtil.strToDateShort(DateUtil.getNextYear(new Date(), -65));
		object.put("code", "3");
		object.put("name", "65岁以上人群");
		object.put("total", doctorPatientDao.countOldPatient(doctor, 0, date));
		
		return object;
	}
	
	
	/**
	 * 查询普通人群
	 * @param doctor
	 * @return
	 */
	public JSONObject findNormalPatient(String doctor) {
		// a.code, a.name, a.photo, a.sex, a.birthday, b.signType
		Date date = DateUtil.strToDateShort(DateUtil.getNextYear(new Date(), -65));
		List<Object> patients = doctorPatientDao.findPatientByDisease(doctor, 0, date);
		return buildPatient(patients, "2", "普通人群");
	}
	
	/**
	 * 查询65岁以上人群
	 * @param doctor
	 * @return
	 */
	public JSONObject findOldPatient(String doctor) {
		// a.code, a.name, a.photo, a.sex, a.birthday, b.signType
		Date date = DateUtil.strToDateShort(DateUtil.getNextYear(new Date(), -65));
		List<Object> patients = doctorPatientDao.findOldPatientByDisease(doctor, 0, date);
		return buildPatient(patients, "other", "65岁以上人群");
	}
	
	private JSONObject buildPatient(List<Object> patients, String team, String teamName){
		JSONObject groupJson = new JSONObject();
		JSONArray groupPatientArray = new JSONArray();
		for (Object temp : patients) {
			Object[] object = (Object[]) temp;
			if (object == null) {
				continue;
			}
			// 患者标识
			Object code = object[1];
			// 姓名
			Object name = object[2];
			// 头像
			Object photo = object[3];
			// 性别
			Object sex = object[4];
			// 生日
			Date birthday = (Date) object[5];
			// 签约类型（1表示三师签约，2表示家庭签约）
			String signType = String.valueOf(object[6]);
			if (StringUtils.equals(signType, "11")) {
				signType = "3";
			} else if (StringUtils.equals(signType, "10")) {
				signType = "1";
			} else if (StringUtils.equals(signType, "01")) {
				signType = "2";
			}
			JSONObject patientJson = new JSONObject();
			// 设置患者标识
			patientJson.put("code", code);
			// 设置患者姓名
			patientJson.put("name", name);
			// 设置患者头像
			patientJson.put("photo", photo);
			// 设置患者年龄
			patientJson.put("age", DateUtil.getAgeByBirthday(birthday));
			// 设置患者性别
			patientJson.put("sex", sex);
			// 设置签约类型
			patientJson.put("signType", signType);
			groupPatientArray.put(patientJson);
		}
		// 设置分组标识
		groupJson.put("code", team);
		// 设置分组名称
		groupJson.put("name", teamName);
		// 设置患者数
		groupJson.put("total", groupPatientArray.length());
		// 设置患者列表
		groupJson.put("patients", groupPatientArray);
		return groupJson;
	}

	/**
	 * 根据分组标识查询分组信息
	 * @param group
	 * @return
	 */
	public DoctorPatientGroup findGroupByCode(String group) {
		return doctorPatientGroupDao.findByCode(group);
	}

	/**
	 * 新建分组
	 * @param doctor 医生标识
	 * @param name 分组名称
	 * @return
	 */
	public DoctorPatientGroup addGroup(String doctor, String name) {
		DoctorPatientGroup dpg = new DoctorPatientGroup();
		// 设置分组标识
		dpg.setCode(getCode());
		// 设置医生标识
		dpg.setDoctor(doctor);
		// 设置分组名称
		dpg.setName(name);
		// 设置分组状态
		dpg.setStatus(1);
		// 设置分组添加时间
		dpg.setCzrq(new Date());
		return doctorPatientGroupDao.save(dpg);
	}

	/**
	 * 删除分组
	 * @param group
	 */
	public int deleteGroup(String group) {
		// 把患者移到other分组
		doctorPatientGroupInfoDao.moveByCode(group);
		return doctorPatientGroupDao.deleteByCode(group);
	}

	/**
	 * 修改组信息
	 * @param group
	 * @return
	 */
	public DoctorPatientGroup modifyGroup(DoctorPatientGroup group) {
		group.setCzrq(new Date());
		return doctorPatientGroupDao.save(group);
	}

	/**
	 * 查询指定医生下的患者自定义分组
	 * @param doctor
	 * @return
	 */
	public List<DoctorPatientGroup> groups(String doctor) {
		return doctorPatientGroupDao.findByDoctor(doctor);
	}

	/**
	 * 查询患者对应医生分组的信息
	 * @param patient
	 * @return
	 */
	public DoctorPatientGroupInfo findGroupInfoByPatient(String doctor, String patient) {
		return doctorPatientGroupInfoDao.findGroupInfoByPatient(doctor, patient);
	}
	
	/**
	 * 是否存在该分组下
	 * @param doctor 医生标识
	 * @param group 分组标识
	 * @param patient 患者标识
	 * @return
	 */
	public int isExistsInGroup(String doctor, String group, String patient) {
		return doctorPatientGroupInfoDao.isExistsInGroup(doctor, group, patient);
	}

	/**
	 * 查询患者坐在分组的信息(有分组名称)
	 * @param patient
	 * @return
	 */
	public DoctorPatientGroup findPatientGroupByPatient(String doctor, String patient) {
		return doctorPatientGroupDao.findPatientGroupByPatient(doctor, patient);
	}

	/**
	 * 添加分组成员
	 * @param list
	 * @return
	 */
	public Iterable<DoctorPatientGroupInfo> addGroupPatients(List<DoctorPatientGroupInfo> list) {
		return doctorPatientGroupInfoDao.save(list);
	}

	/**
	 * 带参数的我的患者查询接口
	 * 
	 * 根据组合条件，获取我的患者列表
	 * 
	 * @param name 患者姓名，模糊匹配
	 * @param groups 分组ID，逗号分隔
	 * @param signType 筛选条件：三师类型
	 * @param diseaseCondition 筛选条件：疾病严重程度，逗号分隔
	 * @param orderDiseaseCondition 排序条件：按病情严重程度排序
	 * @return
	 */
	public List<Map<String, Object>> getPatientsWithFilter(String doctor, String patientName, String groups, String signType, String diseaseCondition, String orderDiseaseCondition) {
		// sql参数集合
		List<Object> args = new ArrayList<Object>();
		// sql语句
		StringBuilder sql = new StringBuilder("select a.group_code, b.code, b.name, b.photo, b.birthday, b.sex, b.disease_condition, b.disease, b.record_amount, a.part_amount, a.qyrq, a.sign_type,b.idcard from wlyy_doctor_patient_group_info a left join wlyy_patient b on a.patient = b.code where  a.doctor = ? and a.status = 1");
		// 当前医生
		args.add(doctor);

		// 名字过滤
		if (!StringUtils.isBlank(patientName)) {
			sql.append(" and b.name like ? ");
			args.add("%" + patientName + "%");
		}

		// 分组过滤
		if (!StringUtils.isBlank(groups)) {
			sql.append(" and a.group_code in (");
			int groupLen = groups.split(",").length;

			for (int i = 0; i < groupLen; i++) {
				sql.append("?");
				if (i < groupLen - 1) {
					sql.append(",");
				}
			}

			sql.append(") ");
			args.addAll(Arrays.asList(groups.split(",")));
		}

		// 签约类型过滤
		if (!StringUtils.isBlank(signType)) {
			sql.append(" and a.sign_type = ? ");
			args.add(signType);
		}

		// 患病严重情况过滤
		if (!StringUtils.isBlank(diseaseCondition)) {
			sql.append(" and b.disease_condition in (");
			int len = diseaseCondition.split(",").length;

			for (int i = 0; i < len; i++) {
				sql.append("?");

				if (i < len - 1) {
					sql.append(",");
				}
			}

			sql.append(") ");
			args.addAll(Arrays.asList(diseaseCondition.split(",")));
		}

		// 按患病严重程度排序
		sql.append(" order by b.disease_condition");

		if (StringUtils.isBlank(orderDiseaseCondition)) {
			// 默认降序排序
			sql.append(" desc");
		} else {
			sql.append(" " + orderDiseaseCondition);
		}
		List<Map<String, Object>> result = jdbcTemplate.queryForList(sql.toString(), args.toArray());

		return result;
	}
	
	/**
	 * 查询患者与医生的关系
	 * @param patient
	 * @param doctor
	 * @return
	 */
	public DoctorPatient findPatientByDoctor(String patient, String doctor){
		DoctorPatient dp = doctorPatientDao.findByPatientDoctorTeamType(patient, doctor, 1);
		if(dp == null){
			dp = doctorPatientDao.findByPatientDoctorTeamType(patient, doctor, 2);
		}
		return dp;
	}
}
